//
//  NewHomepageViewController.m
//  ppkc2016
//
//  Created by Laura on 2017/2/3.
//  Copyright © 2017年 拼凑的断音. All rights reserved.
//

#import "NewHomepageViewController.h"
#import "XXTool.h"
#import "HomepageCell.h"
#import "HomepageTopImgCell.h"
#import "SelectRegistrationStatusViewController.h"
#import "MainViewController.h"
#import "WWSideslipViewController.h"
#import "indexViewController.h"
#import "ExhibitionProfileViewController.h"
#import "ExhibitorElectronicJournalViewController.h"
#import "ConnectUsViewController.h"
#import "PersonInfoViewController.h"

#import "BusinessMatchMakingViewController.h"
#import "XVCCollectPocket.h"
#import "XVCMessage.h"
#import "XVCVisitorMessage.h"
#import "XVCScanQRCode.h"
#import "XVCMapTypeShow.h"

#import "XVCReleaseProduct.h"

#import "SelectRegistrationStatusViewController.h"
#import "PresentProjectMainCotroller.h"

@interface NewHomepageViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>

/**
 *  记录上一次frame的形状
 */
@property (nonatomic,assign) CGRect previousFrame;
/**
 *  记录键盘弹出的高度
 */
//@property (nonatomic,assign,readonly) CGFloat keyboardHeight;
@property (nonatomic) UIImageView * background;
@property (nonatomic) UITableView *tableview;
@property (nonatomic) UIView * line1;
@property (nonatomic) UIView * line2;

@property (nonatomic,strong) WebController *exhibitorWeb;

@property (nonatomic,strong) WebController *visitorWeb;

@property(nonatomic) BOOL isLoadMeassge;  // 已经加载过消息

@end

@implementation NewHomepageViewController
{
    NSMutableArray<HomepageModel*> *HomepageArray;
}

-(WebController*)exhibitorWeb
{
    if (_exhibitorWeb==nil)
    {
        _exhibitorWeb = [[WebController alloc] init];
        _exhibitorWeb.type = WebControllerRootVC;
        _exhibitorWeb.navTit = NSLocalizedString(@"展位预订", nil);
    }
    return _exhibitorWeb;
}

-(WebController*)visitorWeb
{
    if (_visitorWeb==nil)
    {
        _visitorWeb = [[WebController alloc] init];
        _visitorWeb.type = WebControllerRootVC;
        _visitorWeb.navTit = NSLocalizedString(@"观众预登记", nil);
    }
    return _visitorWeb;
}

-(UIImageView*) background
{
    if(_background == nil){
        _background=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bg.jpg"]];
        _background.contentMode=UIViewContentModeScaleToFill;
        [self.view addSubview:_background];
    }
    return _background;
}

-(UITableView*) tableview
{
    if(_tableview ==nil){
        _tableview = [[UITableView alloc] init];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableview];
    }
    return _tableview;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 去掉顶部的bar
    //self.navigationController.navigationBar.hidden=YES;
    //[self.navigationController.navigationBar setBarTintColor:[XXTool colorWithLine]];
    
    NSString* images1[]={@"首页",@"消息",@"联系我们"};
    NSString* images2[]={@"简介",@"收藏夹",@"展位预订"};
    NSString* images3[]={@"会刊",@"扫描二维码",@"观众预登记"};
    NSString* images4[]={@"商贸配对",@"展馆地图",@"我"};
    
    NSString* fflags1[]={@"0",@"4",@"8"};
    NSString* fflags2[]={@"1",@"5",@"9"};
    NSString* fflags3[]={@"2",@"6",@"10"};
    NSString* fflags4[]={@"3",@"7",@"11"};
    
    
    // 获取数据
    HomepageArray=[[NSMutableArray alloc] init];
    for(int i=0;i<3;i++){
        HomepageModel* mode=[[HomepageModel alloc] init];
        
        mode.mode_title1=images1[i];
        mode.mode_image1=images1[i];
        mode.mode_title2=images2[i];
        mode.mode_image2=images2[i];
        mode.mode_title3=images3[i];
        mode.mode_image3=images3[i];
        mode.mode_title4=images4[i];
        mode.mode_image4=images4[i];
        mode.flag1=[fflags1[i] integerValue];
        mode.flag2=[fflags2[i] integerValue];
        mode.flag3=[fflags3[i] integerValue];
        mode.flag4=[fflags4[i] integerValue];
        mode.messageVaild=YES;
        [HomepageArray addObject:mode];
    }
    
//    _previousFrame=CGRectZero;
//    _keyboardHeight=0;
    [self background];
    [self tableview];
    
    self.view.frame=[UIScreen mainScreen].bounds;
    _background.frame=[UIScreen mainScreen].bounds;
    _tableview.frame=CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-20);
    
//    self.view.frame=CGRectMake(self.view.frame.origin.x,
//                               self.view.frame.origin.y,
//                               self.view.frame.size.width,
//                               self.view.frame.size.height);
//    _tableview.frame = CGRectMake(0, 20, self.view.frame.size.width
//                                  , self.view.frame.size.height-20);
    _tableview.backgroundColor=[UIColor clearColor];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickCell:) name:@"successclick" object:nil];
    [self getData];
}

-(void)getData{
    NSString *id=[UserInfo shareUserInfo].userID;
    if( ![id isEqualToString:@""]){
        [DKHTTPRequest sendNewDataWithShortUrl:@"msg_getmsginfo_2017_"
                                         Param:[XXTool formatStringWithLanguage:[NSString stringWithFormat:@"userid=%@&passwd=%@",[UserInfo shareUserInfo].userID,[UserInfo shareUserInfo].userPassword]]
                                    ImageArray:nil
                                       TimeOut:10
                                    Completion:^BOOL(NSMutableDictionary *serverDic, DKHTTPResponseType bufferType) {
                                        if ([[serverDic objectForKey:@"code"] intValue]==200)
                                        {
                                            self.isLoadMeassge=true;
                                            HomepageModel *temp = [HomepageArray objectAtIndex:1];
                                            if ([[serverDic objectForKey:@"value"] intValue]==1)
                                            {
                                                if(temp.flag1 == 4){
                                                    temp.messageVaild = NO;
                                                    temp.messageCount = [NSString stringWithFormat:@"%@",[serverDic objectForKey:@"value2"]];
                                                }else{
                                                    temp.messageVaild = YES;
                                                    temp.messageCount = @"";
                                                }
                                            }
                                            else
                                            {
                                                temp.messageVaild = YES;
                                                temp.messageCount = @"";
                                            }
                                            [_tableview reloadData];
                                            //                                     [_tableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                                        }
                                        return YES;
                                    } IsBuffering:NO
                             IsNeedReplaceWrap:NO
                               IsUseUpLoadHead:NO];
    }
}

-(void)clickCell:(NSNotification *)notification{
    NSLog(@"收到通知了");
    NSInteger tagg=[[notification.userInfo objectForKey:@"tag"] integerValue];
//    if([_delegate newHomepageView:self didClickIndex:tagg isNeedSpecialTreat:NO]){
//        
//    };
    
    //个人中心、商贸配对、消息、收藏夹、联系我们 需要判断是否登录
    if (tagg==11||tagg==3||tagg==4||tagg==5||tagg==8)
    {
        if ([[UserInfo shareUserInfo].userID isEqualToString:@""])
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"提示", nil)
                                                            message:NSLocalizedString(@"您还没有登录,请先登录", nil)
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"取消", nil)
                                                  otherButtonTitles:NSLocalizedString(@"登录", nil), nil];
            [alert show];
            return ;
        }
    }
    
    switch (tagg) {
        case 0:  // 首页
        {
            indexViewController* indexvc=[[indexViewController alloc] init];
            [self.navigationController pushViewController:indexvc animated:YES];
            break;
        }
        case 1:  // 简介
        {
            ExhibitionProfileViewController* exh=[[ExhibitionProfileViewController alloc] init];
            [self.navigationController pushViewController:exh animated:YES];
            break;
        }case 2:  // 会刊
        {
            BOOL is = [[DBProject shareDBProject] isDataBaseUpdating];
            
            if (!is)
            {
                
                NSLog(@"ok");
                
            }
            else
            {
                [SVProgressHUD showInfoWithStatus:@"展商数据更新中..."];
                return ;
            }
            ExhibitorElectronicJournalViewController* huikan=[[ExhibitorElectronicJournalViewController alloc] init];
            [self.navigationController pushViewController:huikan animated:YES];
            
            break;
            
        }
        case 3:  // 商贸配对
        {
            BusinessMatchMakingViewController* bus=[[BusinessMatchMakingViewController alloc] init];
            [self.navigationController pushViewController:bus animated:YES];
            
//            NSArray* targetArray=[viewArray objectForKey:[NSString stringWithFormat:@"%ldPage",(long)index]];
//            if (is)
//            {
//                targetArray = [NSArray arrayWithObjects:[[BusinessMatchMakingViewController alloc]init],[[XVCReleaseProduct alloc] init], nil];
//            }
//            else
//            {
//                targetArray=[NSArray arrayWithObject:[[BusinessMatchMakingViewController alloc]init]];
//            }
//            
//            [main setViewControllers:targetArray animated:NO];
            
            break;
        }
        case 4:  // 消息
        {
            if ([UserInfo shareUserInfo].isExhibitor)
            {
                XVCMessage* xvc=[[XVCMessage alloc] init];
                [self.navigationController pushViewController:xvc animated:YES];
            }else
            {
                XVCVisitorMessage* xvcVi=[[XVCVisitorMessage alloc] init];
                [self.navigationController pushViewController:xvcVi animated:YES];
            }
            
            break;
        }
        case 5:  // 收藏
        {
            XVCCollectPocket* xvcCo=[[XVCCollectPocket alloc] init];
            [self.navigationController pushViewController:xvcCo animated:YES];
            
            break;
        }
        case 6:  // 扫描二维码
        {
            XVCScanQRCode* xvcSc=[[XVCScanQRCode alloc] init];
            [self.navigationController pushViewController:xvcSc animated:YES];
            
            break;
        }
        case 7:  // 展馆地图
        {
            XVCMapTypeShow* xvcMap=[[XVCMapTypeShow alloc] init];
            [self.navigationController pushViewController:xvcMap animated:YES];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ClickMapShow" object:nil];
            break;
        }
        case 8:  // 联系我们
        {
            ConnectUsViewController* connect=[[ConnectUsViewController alloc] init];
            [self.navigationController pushViewController:connect animated:YES];
            
            break;
        }
        case 9:  // 展位登记
        {
            [DKHTTPRequest sendDataWithShortUrl:@"UrlForExhibitor"
                                          Param:[XXTool formatStringWithLanguage:@""]
                                     ImageArray:nil
                                        TimeOut:10
                                     Completion:^BOOL(NSMutableDictionary *serverDic, DKHTTPResponseType bufferType) {
                                         if ([[serverDic objectForKey:@"code"] intValue]==200)
                                         {
                                             [self.exhibitorWeb refreshWebViewWithRequestString:[serverDic objectForKey:@"url"]];
                                         }
                                         
                                         return YES;
                                     } IsBuffering:NO
                              IsNeedReplaceWrap:NO
                                IsUseUpLoadHead:NO];
            
            [self.navigationController pushViewController:self.exhibitorWeb animated:YES];
            
            break;
        }
        case 10:  // 观众预登记
        {
                    [DKHTTPRequest sendDataWithShortUrl:@"UrlForVisitor"
                                          Param:[XXTool formatStringWithLanguage:@""]
                                     ImageArray:nil
                                        TimeOut:10
                                     Completion:^BOOL(NSMutableDictionary *serverDic, DKHTTPResponseType bufferType) {
                                         if ([[serverDic objectForKey:@"code"] intValue]==200)
                                         {
                                             [self.visitorWeb refreshWebViewWithRequestString:[serverDic objectForKey:@"url"]];
                                         }
                                         
                                         return YES;
                                     } IsBuffering:NO
                              IsNeedReplaceWrap:NO
                                IsUseUpLoadHead:NO];
            
            [self.navigationController pushViewController:self.visitorWeb animated:YES];
            
            break;
        }
        case 11:  // 我
        {
            PersonInfoViewController* person=[[PersonInfoViewController alloc] init];
            [self.navigationController pushViewController:person animated:YES];
            
            break;
        }
            
        default:
            break;
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/**
 * 视图即将消失显示
 */
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

/**
 视图即将呈现时隐
 *  添加通知+监听
 *
 *  @param animated 系统参数
 */
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    //self.navigationController.navigationBarHidden=YES;
    /*
     [[NSNotificationCenter defaultCenter] addObserver:self
     selector:@selector(listenInternetState:)
     name:kReachableNotificationReachable
     object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self
     selector:@selector(listenInternetState:)
     name:kReachableNotificationUnreachable
     object:nil];
     */
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardAppear:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardDisappear)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    //[MobClick beginLogPageView:[NSString stringWithUTF8String:object_getClassName(self)]];
    
     [self getData];
    
}

/**
 *  检查布局是否需要改变
 */
-(void)checkLayout
{
//    CGRect reviseFrame=self.view.frame;//修正的frame
//    reviseFrame.size.height-=_keyboardHeight;
//    if(CGRectEqualToRect(_previousFrame, reviseFrame))
//    {//形状相同，则不通知刷新布局
//        
//    }
//    else
//    {//形状不同，通知刷新布局，且记录新布局
//        _previousFrame=reviseFrame;
//        [self refreshLayout:_previousFrame];
//    }
}

/**
 *  键盘弹起时触发
 *
 *  @param notification 通知
 */
-(void)keyboardAppear:(NSNotification*)notification
{
//    CGRect keyboardBounds;
//    [[notification.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardBounds];
//    _keyboardHeight=keyboardBounds.size.height;
//    [self checkLayout];
}

/**
 *  键盘收起时触发
 */
-(void)keyboardDisappear
{
//    _keyboardHeight=0;
    [self checkLayout];
}

/**页面布局调整*/
-(void)refreshLayout:(CGRect)frame
{
    _background.frame=CGRectMake(0, 0, frame.size.width, frame.size.height);
    _tableview.frame = CGRectMake(0, 20, frame.size.width
                                  , frame.size.height);
}

#pragma mark tableviewDatasource
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0)
    {
        return [UIScreen mainScreen].bounds.size.width*554/750;
    }
    else if (indexPath.row==1)
    {
        return 4;
    }else if (indexPath.row==5)
    {
        return 2;
    }
    else
    {
//        return [ExhibitionProfileCell getHeightForExhibitionProfileCell:exhibitionProfileShowTitleArray[indexPath.row-2]];
        return 101;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 6;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0)
    {
        NSString* reuseIdentifier = @"TopImageCell";
        HomepageTopImgCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if(cell==nil)
        {
            cell = [[HomepageTopImgCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor=[UIColor clearColor];
        }
        return cell;
    }
    else if (indexPath.row==1)
    {
        NSString* reuseIdentifier = @"ExhibitionImgCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if(cell==nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor=[UIColor clearColor];
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0
                                                                    , 0
                                                                    , [UIScreen mainScreen].bounds.size.width
                                                                    , 4)];
            line.backgroundColor = [XXTool colorWithHexString:@"ffffff"];
            [cell addSubview:line];
        }
        return cell;
    }
    else if (indexPath.row==5)
    {
        NSString* reuseIdentifier = @"ExhibitionbottomImgCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if(cell==nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor=[UIColor clearColor];
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0
                                                                    , 0
                                                                    , [UIScreen mainScreen].bounds.size.width
                                                                    , 2)];
            line.backgroundColor = [XXTool colorWithHexString:@"ffffff"];
            [cell addSubview:line];
        }
        return cell;
    }
    else
    {
        NSString* reuseIdentifier = @"ExhibitionProfileCell";
        HomepageCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        cell.backgroundColor=[UIColor clearColor];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        if(cell==nil)
        {
            cell = [[HomepageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
            cell.clipsToBounds = YES;
        }
        cell.frame=CGRectMake(0, -30, [UIScreen mainScreen].bounds.size.width, 366);
        [cell setcellWithHomepageData:HomepageArray[indexPath.row-2]];
        return cell;
    }
}

#pragma mark tableviewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    //[tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.row>1 && indexPath.row !=5)
    {
        //HomepageModel* temp=HomepageArray[indexPath.row-2];
       
//        ExhibitionProfileShowTitleModel *temp = exhibitionProfileShowTitleArray[indexPath.row-2];
//        if ([temp.model_type intValue]==3)
//        {
//            WebController *vc = [[WebController alloc] init];
//            vc.type = WebControllerInfoMapUse;
//            vc.request = temp.mode_address;
//            [self.navigationController pushViewController:vc animated:YES];
//        }
    }
}

#pragma mark alertviewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex==1)  // 点击去登录
    {
        SelectRegistrationStatusViewController *vc = [[SelectRegistrationStatusViewController alloc] init];
        vc.isNeedGoIntro = YES;
        [self presentViewController:[[MainViewController alloc] initWithRootViewController:vc] animated:YES completion:^{
        }];
    }
}

@end
